<?php
namespace app\index\controller;

use Des3\DES3;
use Sunra\PhpSimple\HtmlDomParser;
use think\Controller;
use think\Db;
use think\Exception;


vendor('tksdk.TopSdk');


class Index extends Controller
{

    private $_tbconfig = null;
    private $_ftxconfig = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->_tbconfig['app_key'] = '24741714';
        $this->_tbconfig['app_secret'] = 'f2f5a9c7417b0ab85fbda53989b3b5ec';
    }

    public function index(){

    }
    public function sku(){
        halt($this->get_taobao_attribute('https://item.taobao.com/item.htm?id=561669872037'));
    }

    /**
     * 根据淘宝链接，获取商品属性
     * @param string $taobao_url
     * @return array array('材质: 雪纺','形状: 长方形');
     */
    function get_taobao_attribute($taobao_url) {
        $text = file_get_contents($taobao_url);
        return $text;
        $text = iconv('gbk','utf-8//IGNORE', $text);
        preg_match('/<(ul)[^c]*class=\"attributes-list\"[^>]*>.*<\/\\1>/is', $text, $text0);
        preg_match_all("/
]*?>(.*?)<\/li>/i", $text0[0], $contents);
        return $contents[1];
    }


    /**
     * 根据天猫链接，获取商品属性
     * @param string $tmall_url
     * @return array array('货号: YD-905', '材质: 铝合金');
     */
    function get_tmall_attribute($tmall_url) {
        $text = file_get_contents($tmall_url);
        $text = iconv('gbk','utf-8//IGNORE', $text);
        preg_match('/<(ul)[^c]*id=\"J_AttrUL\"[^>]*>.*<\/\\1>/is', $text, $text0);
        preg_match_all("/
]*?>(.*?)<\/li>/i", $text0[0], $contents);
        return $contents[1];
    }
//    public function index()
//    {
//        $c = new \TopClient();
//        $c->appkey = $this->_tbconfig['app_key'];
//        $c->secretKey = $this->_tbconfig['app_secret'];
//        $req = new \TbkUatmEventItemGetRequest();
//        $req->setFields("num_iid,click_url");
//        $req->setNumIids("561921106857");
//        $req->setAdzoneId("41244238");
//        $req->setPlatform("123");
//        $req->setUnid("demo");
//        $req->setDx("1");
//        $resp = $c->execute($req);
//        halt($resp);
//    }
    public function map()
    {
        // 渲染模板输出
        return $this->fetch();

    }
    public function collect()
    {
        $id = 1;//采集器的id
        $auto = 0;//是否自动采集
        $p = 2;//采集页数
        $date = db('robots')->where(array('id' => $id))->find();
        cache('robot_setting', $date);
        if ($date){
            $result_data = $this->api_collect($date, $p);
        }




        if ($auto) {
            if (!$this->_tbconfig['app_key']) {
                $this->ajaxReturn(0, '请设置淘宝appkey');
            }
            $rid = I('rid', 0, 'intval');
            $robots_collect_data['rid'] = $rid;
            $robots_collect_data['p'] = $p;
            F('robots_collect_data', $robots_collect_data);
            if (false === F('robots_time')) {
                F('robots_time', time());
            }
            if (!$rid) {
                $where['status'] = 1;
                $taorobots = $this->_mod->where($where)->order('ordid asc')->select();
                F('taorobots', $taorobots);
                $rid = 0;
            }
            $taorobots = F('taorobots');
            $date = $taorobots[$rid];
            if (!$date) {
                F('totalcoll', NULL);
                F('robots_time', NULL);
                $this->ajaxReturn(0, '一键全自动已经采集完成！请返回，谢谢');
            }
            if ($p > $date['page']) {
                $p = 1;
                $rid = $rid + 1;
                $date = $taorobots[$rid];
                if (!$date) {
                    F('totalcoll', NULL);
                    F('robots_time', NULL);
                    $this->ajaxReturn(0, '一键全自动已经采集完成！请返回，谢谢');
                }
            }
            $np = $p + 1;
            $result_data = $this->api_collect($date, $p);
            $this->assign('result_data', $result_data);
            $msg['title'] = '一键全自动采集';
            $msg['np'] = $np;
            $msg['rid'] = $rid;
            $this->assign('date', $date);
            $this->assign('ftxrobots_count', count($taorobots));
            $this->assign('rids', $rid + 1);
            $resp = $this->fetch('auto_collect');
            $this->ajaxReturn(1, $msg, $resp);
        } else {
            $date = db('robots')->where(array('id' => $id))->find();
            F('robot_setting', $date);
        }
        if ($date) {
            if (!$this->_tbconfig['app_key']) {
                $this->ajaxReturn(0, '请设置淘宝appkey');
            }
            if ($p > $date['page']) {
                F('totalcoll', NULL);
                $this->ajaxReturn(0, '已经采集完成' . $date['page'] . '页！请返回，谢谢');
            }
            $result_data = $this->api_collect($date, $p);
            $this->assign('result_data', $result_data);
            $resp = $this->fetch('collect');
            $this->ajaxReturn(1, '', $resp);
        } else {
            $this->ajaxReturn(0, 'error');
        }
    }

//    public function api_collect($date, $p)
//    {
//        db('robots')->where(array('id' => $date['id']))->update(array('last_page' => $p, 'last_time' => time()));
//        $map['keyword'] = $date['keyword'];  //查询的关键词
//        $map['cid'] = $date['cid'];  //淘宝后台类目的id
//        $map['cate_id'] = $date['cate_id'];  //本站的类目id
//        if ($date['start_commissionRate'] < 100) {    //淘客佣金比率上限
//            $map['start_commissionRate'] = $date['start_commissionRate'] * 100;
//        } else {
//            $map['start_commissionRate'] = $date['start_commissionRate'];
//        }
//        if ($date['end_commissionRate'] < 100) {  //淘客佣金比率下限
//            $map['end_commissionRate'] = $date['end_commissionRate'] * 100;
//        } else {
//            $map['end_commissionRate'] = $date['end_commissionRate'];
//        }
//        $map['start_price'] = $date['start_price'];  //折扣价范围下限，单位：元
//        $map['end_price'] = $date['end_price'];  //折扣价范围上限，单位：元
//        $map['shop_type'] = $date['shop_type']; //是否商城商品，设置为true表示该商品是属于淘宝商城商品，设置为false或不设置表示不判断这个属性
//        $map['recid'] = $date['recid']; //是否更新分类
//        $map['sort'] = $date['sort']; //排序
//        $result = $this->_get_list($map, $p);
//        $taobaoke_item_list = $result['item_list'];
//        $totalnum = $result['count'];
//        $coll = 0;
//        $thiscount = 0;
//        if (is_array($taobaoke_item_list)) {
//            $msg = '成功！';
//        } else {
//            $msg = '失败！';
//        }
//        foreach ($taobaoke_item_list as $key => $val) {
//            $coupon_add_time = C('ftx_coupon_add_time');
//            if ($coupon_add_time) {
//                $times = (int) (strtotime(date("Y-m-d H:00:00", time())) + $coupon_add_time * 3600);
//            } else {
//                $times = (int) (strtotime(date("Y-m-d H:00:00", time())) + 72 * 86400);
//            }
//            $val['coupon_start_time'] = strtotime(date("Y-m-d H:00:00", time()));
//            $val['coupon_end_time'] = $times;
//            $val['astime'] = date("Ymd");
//            $val['recid'] = $map['recid'];
//            $res = $this->_ajax_ftx_publish_insert($val);
//            if ($res > 0) {
//                $coll++;
//
//            }
//            $thiscount++;
//        }
//        F('totalcoll', 0);
//        $result_data['p'] = $p;
//        $result_data['msg'] = $msg;
//        $result_data['coll'] = $coll;
//        $result_data['totalcoll'] = $totalcoll;
//        $result_data['totalnum'] = $totalnum;
//        $result_data['thiscount'] = $thiscount;
//        $result_data['times'] = lefttime(time() - $robots_time);
//        return $result_data;
//    }

    private function _get_list($map, $p)
    {
        $tb_top = $this->_get_tb_top();
        $req = new \TbkItemGetRequest();
        $req->setFields('num_iid,title,nick,pict_url,volume,reserve_price,zk_final_price,user_type,item_url,seller_id');
        $req->setPageSize('40');
        $req->setPageNo($p);
        $map['keyword'] && $req->setQ($map['keyword']);
        $map['cid'] && $req->setCat($map['cid']);
        if ($map['start_price'] && $map['end_price']) {
            $req->setStartPrice(intval($map['start_price']));
            $req->setEndPrice(intval($map['end_price']));
        }
        $map['start_commissionRate'] && $req->setStartTkRate($map['start_commissionRate']);
        $map['end_commissionRate'] && $req->setEndTkRate($map['end_commissionRate']);
        if ($map['shop_type'] == 'B') {
            $req->setIsTmall('true');
        }
        $map['sort'] && $req->setSort($map['sort']);
        $resp = $tb_top->execute($req);
        $count = $resp->total_results;
        $taobaoke_item_list = array();
        $resp_items = (array) $resp->results;
        halt($resp_items);
        if (!$resp_items) {
            return array('count' => intval($count), 'item_list' => $taobaoke_item_list);
            $resul = (array) $resp;
            $this->ajaxReturn(0, $resul['msg']);
        }
        $iids = '';
        foreach ($resp_items['n_tbk_item'] as $val) {
            $val = (array) $val;
            $iid = (string) $val['num_iid'];
            $val['cate_id'] = $map['cate_id'];
            $val['nick'] = $val['nick'];
            $val['pic_url'] = $val['pict_url'];
            $val['price'] = $val['reserve_price'];
            $val['coupon_price'] = $val['zk_final_price'];
            $val['coupon_rate'] = round($val['coupon_price'] / $val['price'], 4) * 10000;
            $val['sellerId'] = $val['seller_id'];
            $val['volume'] = $val['volume'];
            $val['ems'] = 1;
            if ($val['user_type']) {
                $val['shop_type'] = 'B';
            } else {
                $val['shop_type'] = 'C';
            }
            unset($val['reserve_price']);
            unset($val['zk_final_price']);
            unset($val['seller_id']);
            unset($val['pict_url']);
            unset($val['user_type']);
            $taobaoke_item_list[$iid] = $val;
        }
        return array('count' => intval($count), 'item_list' => $taobaoke_item_list);
    }

    private function _get_tb_top()
    {

//        vendor('taobao.RequestCheckUtil');
//        vendor('taobao.ResultSet');
        $tb_top = new \TopClient();
        $tb_top->appkey = $this->_tbconfig['app_key'];
        $tb_top->secretKey = $this->_tbconfig['app_secret'];
        return $tb_top;
    }

    public function cates(){
        $c = new \TopClient();
        $c->appkey = $this->_tbconfig['app_key'];
        $c->secretKey = $this->_tbconfig['app_secret'];
        $req = new \ItemCatsGetRequest();
        $req->setCids("18957,19562");
        $req->setDatetime("2000-01-01 00:00:00");
        $req->setFields("cid,parent_cid,name,is_parent");
        $req->setParentCid("50011999");
        $resp = $c->execute($req);
        halt($resp);
    }

    /**
     * 实现传入宝贝id,获取宝贝价格,支持淘宝和天猫
     * @param $id   宝贝的id
     * @return mixed 返回的宝贝的价格或价格区间
     */
    function getPriceById(){
        $url="http://hws.m.taobao.com/cache/wdetail/5.0/?id=557749536058";
        $content=file_get_contents($url);
        $content_ori=strip_tags($content);
        $content_arr=json_decode($content_ori,true);
        $pro_detail=json_decode($content_arr['data']['apiStack']['0']['value'],true);
        $success_sym=$pro_detail['ret']['0'];//成功则返回"SUCCESS::调用成功";
        if($success_sym=="SUCCESS::调用成功"){
            $pro_price=$pro_detail['data']['itemInfoModel']['priceUnits']['0']['price'];
            return $pro_price;
        }else{
            return "<script type='text/javascript'>alert('宝贝不存在!');</script>";
        }
    }

    public function api(){
        $url="http://hws.m.taobao.com/cache/wdetail/5.0/?id=557749536058";
        $content=file_get_contents($url);
        $content_ori=strip_tags($content);
        $content_arr=json_decode($content_ori,true);
        $value = json_decode($content_arr['data']['apiStack'][0]['value'],true);

        halt($value['data']['skuModel']['skus']);
    }

    public function get_info(){
        $url="http://hws.m.taobao.com/cache/wdetail/5.0/?id=560937014821";
        $content=file_get_contents($url);
        $content_ori=strip_tags($content);
        $content_arr=json_decode($content_ori,true);
        $skuProps = $content_arr['data']['skuModel']['skuProps'];
        $values = json_decode($content_arr['data']['apiStack'][0]['value'],true);
        $sku_info = [];
        foreach ($skuProps as $k=>$v){
            foreach ($v['values'] as $key=>$value){
                $sku_info[$k]['propids'][]= $v['propId'].':'.$value['valueId'].';';
                $sku_info[$k]['name'][]= $value['name'].' ';
            }
            $sku_ids[] = $sku_info[$k]['propids'];
            $sku_name[] = $sku_info[$k]['name'];
        }
        $new_arr['ids'] = $this->zuhe($sku_ids);
        $new_arr['names'] = $this->zuhe($sku_name);
        foreach ($new_arr['ids'][0] as $t=>$vl){
            $new_arr['ids'][0][$t] = trim($new_arr['ids'][0][$t],'/;/:');
            $new_arr['names'][0][$t] = trim($new_arr['names'][0][$t],'/ /:');
            $new_arr['skuid'][0][$t] = $content_arr['data']['skuModel']['ppathIdmap'][ $new_arr['ids'][0][$t]];
            if (!isset($values['data']['skuModel']['skus'][$new_arr['skuid'][0][$t]]['priceUnits'][0]['price'])){
                $new_arr['price'][0][$t] = 0;
            }else{
                $new_arr['price'][0][$t] = $values['data']['skuModel']['skus'][$new_arr['skuid'][0][$t]]['priceUnits'][0]['price'];
            }

        }
        dump($new_arr);
    }

    function zuhe($arr){
        if(count($arr) >= 2){
            $tmparr = array();
            $arr1 = array_shift($arr);
            $arr2 = array_shift($arr);
            foreach($arr1 as $k1 => $v1){
                foreach($arr2 as $k2 => $v2){
                    $tmparr[] = $v1.$v2;
                }
            }
            array_unshift($arr, $tmparr);
            $arr = $this->zuhe($arr);
        }else{
            return $arr;
        }
        return $arr;
    }

    function send_code(){
        $data = \app\api\common\Common::send_note(['phone'=>'18850459208','type'=>1]);
        halt($data);
    }

    function getc(){
        $data = \app\api\common\Goods::category(1);
        halt($data);
    }
    function getl(){
        $data = \app\api\common\Shop::nearby_shop(['lat'=>'24.51574','lng'=>'118.13752']);
        halt($data);
    }
    function getcl(){
        $data = \app\api\common\Shop::shop_class(['id'=>1]);
        halt($data);
    }
    function getct(){
        $data = \app\api\common\Task::accept_task(['member_id'=>1,'demand_id'=>66]);
        halt($data);
    }
    function task_info(){
        $data = \app\api\common\Task::super_buyer(['member_id'=>1,'task_id'=>256]);
        halt($data);
    }
    function indexa(){
        $data = \app\api\common\Index::index(['lat'=>'24.51574','lng'=>'118.13752']);
        halt($data['data']['shop_list']);
    }
    function cat_goods(){
        $data = \app\api\common\Index::cat_goods(['cat_id'=>1,'page'=>1]);
        dump($data['data']['results']);
    }
    public function ocr(){
        header("Content-type: image/png");
        vendor('aip.AipOcr');
        $client = new \AipOcr('10865020','SM5c9WywaNkXlsWWMsT2G4Ga','2uwrsKdT2drWAZviqo4hbRqC4HkCzfE0');

//        $image = file_get_contents('https://bpic.588ku.com/original_origin_min_pic/18/04/13/3eff7bdc11ee18ee357d03e275c54e33.jpg!r650');


// 调用通用文字识别, 图片参数为远程url图片
//        $client->basicGeneralUrl('http://order-1252067342.picsh.myqcloud.com/Screenshot_2018-02-28-11-43-10-336_com.taobao.tao.png');

// 如果有可选参数
        $options = array();
        $options["language_type"] = "CHN_ENG";
        $options["detect_direction"] = "true";
        $options["detect_language"] = "true";
        $options["probability"] = "true";

// 带参数调用通用文字识别, 图片参数为远程url图片
        $data = $client->basicGeneralUrl('http://lantaoke.net/getVcode.php', $options);

        halt($data);

    }

    public function get_good($i=1,$url = "http://v2.api.haodanku.com/itemlist/apikey/shen/nav/3/cid/1/back/1000/min_id/1"){
        if ($i<17){
            $data = file_get_contents($url);
            $content_ori=strip_tags($data);
            $content_arr=json_decode($content_ori,true);
            foreach ($content_arr['data'] as $k=>$v){
                if ($v['activityid'])
                    $content_arr['data'][$k]['couponurl'] = "https://uland.taobao.com/coupon/edetail?activityId=".$v['activityid']."&pid=mm_31559946_41244238_187498430&itemId=".$v['itemid']."&src=cd_cdll";
                unset($content_arr['data'][$k]['me'],$content_arr['data'][$k]['original_article'],$content_arr['data'][$k]['original_img'],$content_arr['data'][$k]['seller_name'],$content_arr['data'][$k]['general_index'],$content_arr['data'][$k]['report_status'],$content_arr['data'][$k]['cuntao'],$content_arr['data'][$k]['online_users']);
                unset($content_arr['data'][$k]['planlink'],$content_arr['data'][$k]['discount'],$content_arr['data'][$k]['isquality'],$content_arr['data'][$k]['seller_id'],$content_arr['data'][$k]['couponsurplus'],$content_arr['data'][$k]['couponreceive']);
                unset($content_arr['data'][$k]['todaycouponreceive'],$content_arr['data'][$k]['starttime']);
            }
            Db::table('yf_items')->insertAll($content_arr['data'],true);
            ob_flush();
            flush();
            sleep(2);
            if ($k == 999){
                $url = "http://v2.api.haodanku.com/itemlist/apikey/shen/nav/3/cid/".$i."/back/1000/min_id/".$content_arr['min_id'];
                $this->get_good($i,$url);
            }else{
                $i++;
                $url = "http://v2.api.haodanku.com/itemlist/apikey/shen/nav/3/cid/".$i."/back/1000/min_id/1";
                $this->get_good($i,$url);
            }

        }else{
            echo '完成';
        }


//            sleep(2);
//            if ($k == 999){
//                $url = "http://v2.api.haodanku.com/itemlist/apikey/shen/nav/3/cid/".$i."/back/1000/min_id/".$content_arr['min_id'];
//                break;
//            }else{
//                $i++;
//                $url = "http://v2.api.haodanku.com/itemlist/apikey/shen/nav/3/cid/".$i."/back/1000/min_id/1";
//                break;
//            }
//
//        }
//        echo $i;
//        dump($content_arr['min_id']);
//        $this->get_good($i,$url);

    }
    public function test_good(){
        $url = "http://v2.api.haodanku.com/itemlist/apikey/shen/nav/3/cid/13/back/1000/min_id/4019774";
        $data = file_get_contents($url);
        $content_ori=strip_tags($data);
        $content_arr=json_decode($content_ori,true);
        halt($content_arr);
    }

    public function goods_del(){
        $data = Db::table('yf_items')->where(['end_time'=>['lt',time()]])->whereOr(['couponendtime'=>['lt',time()]])->select();
        halt($data);




        Db::startTrans();
        try{

            if (Db::table('yf_items')->where(['end_time'=>['lt',time()]])->whereOr(['couponendtime'=>['lt',time()]])->delete()){
                Db::commit();
                echo 'success';
            }else{
                throw new Exception('错误');
            }

        }catch (Exception $e){
            Db::rollback();
            echo $e->getMessage();
        }

    }

    public function lyt(){
        $data = \app\api\common\Shop::shop_goods(['shop_id'=>25,'class_id'=>1]);
        halt($data);
    }

    public function import_goods(){
        $shop_id = input('param.shop_id',0);
        if ($shop_id == 0){
            exit('店铺id');
        }
        for ($i=1;$i<17;$i++){
            $data = Db::name('items')->field('fqcat,itemid,itemtitle,itemprice,itempic,shoptype')->where(['fqcat'=>$i,'couponstarttime'=>['lt',time()],'couponendtime'=>['gt',time()],'start_time'=>['lt',time()],'end_time'=>['gt',time()]])->limit('60')->select();
           $info = [];
            foreach ($data as $k=>$v){
                $info[$k]['cat_id'] = $data[$k]['fqcat'];
                $info[$k]['goods_name'] = $data[$k]['itemtitle'];
                $info[$k]['click_count'] = 30;
                $info[$k]['store_count'] = 20;
                $info[$k]['price'] = $data[$k]['itemprice'];
                $info[$k]['original_img'] = $data[$k]['itempic'];
                $info[$k]['is_on_sale'] = 1;
                $info[$k]['is_recommend'] = 1;
                $info[$k]['is_new'] = 1;
                $info[$k]['is_hot'] = 1;
                $info[$k]['last_update'] = time();
                $info[$k]['suppliers_id'] = 0;
                $info[$k]['sales_sum'] = 10;
                $info[$k]['shop_id'] = $shop_id;
                $info[$k]['purchase_id'] = 0;
                $info[$k]['tb_id'] = $data[$k]['itemid'];
            }
            unset($data);
            Db::name('goods')->insertAll($info);
            echo $i;
            dump($info);
            unset($info);
        }
        echo "完成";
    }

    public function get_goodd(){
        $ch = curl_init();
        //设置选项
        curl_setopt($ch,CURLOPT_URL,'http://hws.m.taobao.com/cache/wdetail/5.0/?id=557749536058');
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
        curl_setopt($ch, CURLOPT_REFERER, "http://hws.m.taobao.com/cache/wdetail/5.0/?id=557749536058");
        $header = array();
        $header[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8';
        $header[] = 'Accept-Language: zh-CN,zh;q=0.8';
        $header[] = 'Cache-Control: max-age=0';
        $header[] = 'Connection: keep-alive';
        $header[] = 'Cookie: uc3=nk2=0M56YNYN%2BA4%3D&id2=W8rr4uUwfV5Z&vt3=F8dAT%2B%2BMdeVt9sjBn%2Bk%3D&lg2=WqG3DMC9VAQiUQ%3D%3D; lgc=%5Cu695A%5Cu5929%5Cu5B9D%5Cu9676; tracknick=%5Cu695A%5Cu5929%5Cu5B9D%5Cu9676; t=45643498fa8ff940a0534abf468c496b; _tb_token_=5touPdVYykOo; cookie2=9cc3ace3ba141f7e0e950da7b4782eae; tt=segmentfault.com; res=scroll%3A1349*6222-client%3A1349*667-offset%3A1349*6222-screen%3A1366*768; pnm_cku822=055UW5TcyMNYQwiAiwQRHhBfEF8QXtHcklnMWc%3D%7CUm5Ockt1T3BEf0N%2BSnJPciQ%3D%7CU2xMHDJ7G2AHYg8hAS8WKQcnCVU0Uj5ZJ11zJXM%3D%7CVGhXd1llXGJYZ1NoVGldZVhlUm9NeEd9SHFFfElyR35Be0N%2FR2k%2F%7CVWldfS0TMwY8ACAcKQkncVU4XSNKGn9AZE8BUDxQCW4PIXch%7CVmhIGCUFOBgkGiMXNwwzDDMTLxEqETELMAUlGSccJwc9AjdhNw%3D%3D%7CV25Tbk5zU2xMcEl1VWtTaUlwJg%3D%3D; cq=ccp%3D1; l=AikpB1ewOIvOADHsO87Aa9qtuduD9B0s; otherx=e%3D1%26p%3D*%26s%3D0%26c%3D0%26f%3D0%26g%3D0%26t%3D0; swfstore=142738; isg=4C03295B995DB1CB7ADB1CC702592A48';
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        //执行并获取HTML文档内容
        $data = curl_exec($ch);
        curl_close($ch);
        halt($data);
    }

    public function del_goods(){

        Db::startTrans();
        try{
            Db::table('yf_items')->where(['couponendtime'=>['lt',time()],'end_time'=>['lt',time()]])->delete();
            Db::commit();
            echo '删除成功';
        }catch (Exception $e){
            Db::rollback();
            echo '删除失败'.$e->getMessage();
        }


    }

    public function get_data(){
        $url='https://detailskip.taobao.com/service/getData/1/p1/item/detail/sib.htm?itemId=564999296838&sellerId=3822895367&modules=dynStock,qrcode,viewer,price,duty,xmpPromotion,delivery,activity,fqg,zjys,couponActivity,soldQuantity,originalPrice,tradeContract&callback=onSibRequestSuccess';
        $url_refer = 'https://item.taobao.com';
        $ch = curl_init();
        //设置选项
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
        curl_setopt($ch, CURLOPT_REFERER, $url_refer);
        $header = array();
        $header[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8';
        $header[] = 'Accept-Language: zh-CN,zh;q=0.8';
        $header[] = 'Cache-Control: max-age=0';
        $header[] = 'Connection: keep-alive';
        $header[] = 'Cookie: uc3=nk2=0M56YNYN%2BA4%3D&id2=W8rr4uUwfV5Z&vt3=F8dAT%2B%2BMdeVt9sjBn%2Bk%3D&lg2=WqG3DMC9VAQiUQ%3D%3D; lgc=%5Cu695A%5Cu5929%5Cu5B9D%5Cu9676; tracknick=%5Cu695A%5Cu5929%5Cu5B9D%5Cu9676; t=45643498fa8ff940a0534abf468c496b; _tb_token_=5touPdVYykOo; cookie2=9cc3ace3ba141f7e0e950da7b4782eae; tt=segmentfault.com; res=scroll%3A1349*6222-client%3A1349*667-offset%3A1349*6222-screen%3A1366*768; pnm_cku822=055UW5TcyMNYQwiAiwQRHhBfEF8QXtHcklnMWc%3D%7CUm5Ockt1T3BEf0N%2BSnJPciQ%3D%7CU2xMHDJ7G2AHYg8hAS8WKQcnCVU0Uj5ZJ11zJXM%3D%7CVGhXd1llXGJYZ1NoVGldZVhlUm9NeEd9SHFFfElyR35Be0N%2FR2k%2F%7CVWldfS0TMwY8ACAcKQkncVU4XSNKGn9AZE8BUDxQCW4PIXch%7CVmhIGCUFOBgkGiMXNwwzDDMTLxEqETELMAUlGSccJwc9AjdhNw%3D%3D%7CV25Tbk5zU2xMcEl1VWtTaUlwJg%3D%3D; cq=ccp%3D1; l=AikpB1ewOIvOADHsO87Aa9qtuduD9B0s; otherx=e%3D1%26p%3D*%26s%3D0%26c%3D0%26f%3D0%26g%3D0%26t%3D0; swfstore=142738; isg=4C03295B995DB1CB7ADB1CC702592A48';
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        //执行并获取HTML文档内容
        $data = curl_exec($ch);
        curl_close($ch);
        $searchString = "onSibRequestSuccess(";
        $firstLength = strpos($data, $searchString);
        $length = $firstLength + strlen($searchString);
        $str = substr(substr($data, $length), 0, -2);
        $output_array = json_decode($str,true);
//        halt($output_array['data']['tradeContract']);
//        halt($output_array['data']['dynStock']);
//        halt($output_array['data']['couponActivity']['coupon']);
        halt($output_array['data']['promotion']['promoData']);
    }

    //获取淘宝天猫的sku信息
    public function get_skuinfo(){
        $is_tmall = input('param.is_tmall','C');
        $itemid = input('param.itemid',0);
        if ($itemid == 0){
            throw new Exception('商品ID未传');
        }
        if ($is_tmall == 'B'){ //天猫
            $url = 'https://detail.tmall.com/item.htm?id='.$itemid;
            $dom = HtmlDomParser::file_get_html($url);
            $start1=strstr($dom,"{\"api\"");
            $tp = strpos($start1,"</script>");
            $str = substr($start1,0,$tp);
            $str=iconv("GBK", "UTF-8", $str);
            $new_str = substr($str, 0, -11);
            $arr = json_decode($new_str,true);
            if (!isset($arr['valItemInfo'])){
                $list = $this->get_datas($itemid,'B',1);
            }else{
                foreach ($arr['valItemInfo']['skuList'] as $k=>$v){
                    if ($arr['valItemInfo']['skuMap'][';'.$v['pvs'].';']['stock'] == 0){
                        continue;
                    }else{
                        $list[] = $v;
                    }
                }
                $list_info = $this->get_datas($itemid,'B','');
                foreach ($list as $key=>$vv){
                    foreach ($list_info as $value){
                        if ($value['sku_id'] == $vv['skuId']){
                            $list[$key]['price'] = $value['price'];
                            break;
                        }
                    }
                }
            }
        }else{
            $url = 'https://item.taobao.com/item.htm?id='.$itemid;
            $dom = HtmlDomParser::file_get_html($url);
            $start1=strstr($dom,"propertyMemoMap:");
            $tp = strpos($start1," Hub.config.set");
            $str = substr($start1,0,$tp);
            $str=iconv("GBK", "UTF-8", $str);
            $new_str = substr($str, 16, -14);
            $arr = json_decode($new_str,true);
            //获取sku名称
            $u = $dom->find(".tb-skin",0);
            $lins =[];
            $lin = [];
            foreach ($u->find('.J_Prop') as $key=>$elemt){
                if (mb_convert_encoding($elemt->find('dt',0)->innertext(), "UTF-8", "GBK") == '数量' || mb_convert_encoding($elemt->find('dt',0)->innertext(), "UTF-8", "GBK") == '花呗分期'){
                    continue;
                }
                foreach ($elemt->find('li') as $k=>$lit){
                    $name[$k]= mb_convert_encoding($lit->find('span',0)->innertext(), "UTF-8", "GBK").' ';
                    $sku_value[$k] =';'. mb_convert_encoding($lit->getAttribute('data-value'), "UTF-8", "GBK");
                }
                $lin[$key] = $name;
                $lins[$key] = $sku_value;
                $name = [];
                $sku_value = [];
            }
            if (!empty($lins)){
                $result = $this->zuhe($lins);
                foreach ($result[0] as $k=>$v){
                    $sku_list[$k] = $v.';';
                }
                $re = $this->zuhe($lin);
                $result_info['name'] =  $re[0]; //sku名称
                $result_info['pvs'] =  $sku_list; //sku pvs
                foreach ($sku_list as $k=>$v){
                    $data[$v] = $re[0][$k];
                }
                $list = $this->get_datas($itemid,'C');
                halt($list);
                foreach ($list as $key=>$val){
                    $list[$key]['names'] = $data[$val['pvs']];
                }
            }else{
                $list = $this->get_datas($itemid,'C',1);
            }
        }
        return $list;

    }

    public function get_datas($id,$is_tmall,$is_default=0){
        if ($is_tmall == 'B'){
            $url='https://mdskip.taobao.com/core/initItemDetail.htm?isUseInventoryCenter=false&cartEnable=true&service3C=false&isApparel=true&isSecKill=false&tmallBuySupport=true&isAreaSell=false&tryBeforeBuy=false&offlineShop=false&itemId='.$id.'&showShopProm=false&cachedTimestamp=1522308759411&isPurchaseMallPage=false&isRegionLevel=false&household=false&sellerPreview=false&queryMemberRight=true&addressLevel=2&isForbidBuyItem=false&callback=setMdskip&timestamp=1522315551231&isg=null&isg2=BHd3HcgO4fKkX2WfBKIeJNztBmsBlEv2mG-N6cklgMateJO60QmK7HU5XtgmkCMW&areaId=350200&cat_id=2&ref=https%3A%2F%2Flist.tmall.com%2Fsearch_product.htm%3Fq%3D%25D2%25C2%25B7%25FE%26type%3Dp%26spm%3Da220o.0.a2227oh.d100%26from%3D.detail.pc_1_searchbutton';
        }else{
            $url='https://detailskip.taobao.com/service/getData/1/p1/item/detail/sib.htm?itemId='.$id.'&modules=dynStock,qrcode,viewer,price,duty,xmpPromotion,delivery,upp,activity,fqg,zjys,amountRestriction,couponActivity,soldQuantity,originalPrice,tradeContract&callback=onSibRequestSuccess';
        }
        $url_refer = 'https://item.taobao.com';
        $ch = curl_init();
        //设置选项
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
        curl_setopt($ch, CURLOPT_REFERER, $url_refer);
        $header = array();
        $header[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8';
        $header[] = 'Accept-Language: zh-CN,zh;q=0.8';
        $header[] = 'Cache-Control: max-age=0';
        $header[] = 'Connection: keep-alive';
        $header[] = 'Cookie: uc3=nk2=0M56YNYN%2BA4%3D&id2=W8rr4uUwfV5Z&vt3=F8dAT%2B%2BMdeVt9sjBn%2Bk%3D&lg2=WqG3DMC9VAQiUQ%3D%3D; lgc=%5Cu695A%5Cu5929%5Cu5B9D%5Cu9676; tracknick=%5Cu695A%5Cu5929%5Cu5B9D%5Cu9676; t=45643498fa8ff940a0534abf468c496b; _tb_token_=5touPdVYykOo; cookie2=9cc3ace3ba141f7e0e950da7b4782eae; tt=segmentfault.com; res=scroll%3A1349*6222-client%3A1349*667-offset%3A1349*6222-screen%3A1366*768; pnm_cku822=055UW5TcyMNYQwiAiwQRHhBfEF8QXtHcklnMWc%3D%7CUm5Ockt1T3BEf0N%2BSnJPciQ%3D%7CU2xMHDJ7G2AHYg8hAS8WKQcnCVU0Uj5ZJ11zJXM%3D%7CVGhXd1llXGJYZ1NoVGldZVhlUm9NeEd9SHFFfElyR35Be0N%2FR2k%2F%7CVWldfS0TMwY8ACAcKQkncVU4XSNKGn9AZE8BUDxQCW4PIXch%7CVmhIGCUFOBgkGiMXNwwzDDMTLxEqETELMAUlGSccJwc9AjdhNw%3D%3D%7CV25Tbk5zU2xMcEl1VWtTaUlwJg%3D%3D; cq=ccp%3D1; l=AikpB1ewOIvOADHsO87Aa9qtuduD9B0s; otherx=e%3D1%26p%3D*%26s%3D0%26c%3D0%26f%3D0%26g%3D0%26t%3D0; swfstore=142738; isg=4C03295B995DB1CB7ADB1CC702592A48';
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        //执行并获取HTML文档内容
        $data = curl_exec($ch);
        curl_close($ch);
        if ($is_tmall == 'B'){
            $searchString = "setMdskip (";
            $firstLength = strpos($data, $searchString);
            $length = $firstLength + strlen($searchString);
            $str = substr(substr($data, $length), 1,-1);
            $str = strip_tags($str);
            $str = mb_convert_encoding($str, "UTF-8", "GBK");
            $output_array = json_decode($str,true);
            if ($is_default == 1){
                $def = [];
                if (!empty($output_array['defaultModel']['itemPriceResultDO']['priceInfo']['def']['promotionList'])){
                    $def[0]['price'] = $output_array['defaultModel']['itemPriceResultDO']['priceInfo']['def']['promotionList'][0]['price'];
                    $def[0]['names'] = '';
                    $def[0]['pvs'] = '';
                }else{
                    $def[0]['price'] = $output_array['defaultModel']['itemPriceResultDO']['priceInfo']['def']['price'];
                    $def[0]['names'] = '';
                    $def[0]['pvs'] = '';
                }
                return $def;
            }
            $key_list = array_keys($output_array['defaultModel']['itemPriceResultDO']['priceInfo']);
            foreach ($key_list as $k=>$v){
                $arr[$k]['sku_id'] = $v;
                if (!empty($output_array['defaultModel']['itemPriceResultDO']['priceInfo'][$v]['promotionList'])){
                    $arr[$k]['price'] = $output_array['defaultModel']['itemPriceResultDO']['priceInfo'][$v]['promotionList'][0]['price'];
                }else{
                    $arr[$k]['price'] = $output_array['defaultModel']['itemPriceResultDO']['priceInfo'][$v]['price'];
                }
            }
        }else{
            $searchString = "onSibRequestSuccess(";
            $firstLength = strpos($data, $searchString);
            $length = $firstLength + strlen($searchString);
            $str = substr(substr($data, $length), 0,-2);
            $str = strip_tags($str);
            $str = mb_convert_encoding($str, "UTF-8", "GBK");
            $output_array = json_decode($str,true);
            if ($is_default==1){

                if (!empty($output_array['data']['promotion']['promoData'])){
                    $def[0]['price'] = $output_array['data']['promotion']['promoData']['def'][0]['price'];
                    $def[0]['names'] = '';
                    $def[0]['pvs'] = '';
                }else{
                    $def[0]['price'] = $output_array['data']['originalPrice']['def']['price'];
                    $def[0]['names'] = '';
                    $def[0]['pvs'] = '';
                }
                return $def;
            }
            $pvs = [];
            foreach ($output_array['data']['dynStock']['sku'] as $k=>$v){
                if ($v['stock'] == 0){
                    continue;
                }else{
                    $pvs[]=$k;
                }
            }
            $arr = [];
            if (empty($output_array['data']['promotion']['promoData'])){
                foreach ($pvs as $key=>$value){
                    $arr[$key]['pvs'] = $value;
                    $arr[$key]['price'] = $output_array['data']['originalPrice'][$value]['price'];
                }
            }else{
                foreach ($pvs as $key=>$value){
                    $arr[$key]['pvs'] = $value;
                    if (isset($output_array['data']['promotion']['promoData']['def'][$value])){
                        $arr[$key]['price'] = $output_array['data']['promotion']['promoData']['def'][$value][0]['price'];
                    }else{
                        $arr[$key]['price'] = $output_array['data']['originalPrice'][$value]['price'];
                    }

                }
            }
        }
        return $arr;
    }






    //参数1：访问的URL，参数2：post数据(不填则为GET)，参数3：提交的$cookies,参数4：是否返回$cookies
    public function curl_requests($url,$post='',$cookie='', $returnCookie=0){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        curl_setopt($curl, CURLOPT_REFERER, "http://XXX");
        if($post) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
        }
        if($cookie) {
            curl_setopt($curl, CURLOPT_COOKIE, $cookie);
        }
        curl_setopt($curl, CURLOPT_HEADER, $returnCookie);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        if (curl_errno($curl)) {
            return curl_error($curl);
        }
        curl_close($curl);
        if($returnCookie){
            list($header, $body) = explode("\r\n\r\n", $data, 2);
            preg_match_all("/Set\-Cookie:([^;]*);/", $header, $matches);
            $info['cookie']  = substr($matches[1][0], 1);
            $info['content'] = $body;
            return $info;
        }else{
            $output_array = json_decode($data,true);
            return $output_array;
        }
    }

    function zuhe2($arr){
        if(count($arr) >= 2){
            $tmparr = array();
            $arr1 = array_shift($arr);
            $arr2 = array_shift($arr);
            foreach($arr1 as $k1 => $v1){
                foreach($arr2 as $k2 => $v2){
                    $tmparr[] = $v1.' '.$v2;
                }
            }
            array_unshift($arr, $tmparr);
            $arr = $this->zuhe($arr);
        }else{
            return $arr;
        }
        return $arr;
    }

    function zuhe3($arr){
        if(count($arr) >= 2){
            $tmparr = array();
            $arr1 = array_shift($arr);
            $arr2 = array_shift($arr);
            foreach($arr1 as $k1 => $v1){
                foreach($arr2 as $k2 => $v2){
                    $tmparr[] = $v1.$v2;
                }
            }
            array_unshift($arr, $tmparr);
            $arr = $this->zuhe($arr);
        }else{
            return $arr;
        }
        return $arr;
    }


    public function get_regions(){
        $data = Db::name('regions')->field('region_name,region_code,lat,lng,pinyin')->where(['level'=>2])->select();
        $str = json_encode($data,JSON_UNESCAPED_UNICODE);
        echo $str.'2';
    }

    public function get_ip(){
        $data = getIpInfo();
        halt($data);
    }

    public function goods()
    {
        $data = Db::table('yf_goods')->field('id,shop_id', true)->where(['shop_id' => 23])->select();
        $shops = Db::table('yf_shop')->field('id')->where(['id' => ['gt', 30]])->select();
        foreach ($shops as $k => $v) {
            foreach ($data as $key => $val) {
                $data[$key]['shop_id'] = $v['id'];
            }
            $flag = Db::table('yf_goods')->insertAll($data);
            if ($flag) {
                echo $v['id'] . '<br>';
            } else {
                echo '错误' . $v['id'];
            }
        }
    }

    public function address(){
        $shops = Db::table('yf_shop')->field('id,lng,lat')->select();
        foreach ($shops as $k=>$v){
            $url = 'http://restapi.amap.com/v3/geocode/regeo?key=ac0d52fa844fe018d8e609446eac65a6&location='.$v['lng'].','.$v['lat'].'&poitype=&radius=0&extensions=base&batch=false&roadlevel=0';
            $data = file_get_contents($url);
            $content=strip_tags($data);
            $content_arr=json_decode($content,true);
            if ($content_arr['infocode'] == '10000'){
                Db::table('yf_shop')->where('id',$v['id'])->setField('citycode', $content_arr['regeocode']['addressComponent']['citycode']);
            }else{
                echo $v['id'].'<br>';
            }
        }
    }

    public function in(){
        $data = \app\api\common\Index::index(['lat'=>'24.500106','lng'=>'118.127054']);
        halt($data['data']);
    }
    public function del_item(){
        $id = input('param.cat_id',1);
        $item_id = Db::table('yf_items')->where(['tktype'=>'定向计划','fqcat'=>$id])->delete();
        if ($item_id){
            echo $item_id.'<br>';
        }else{
            echo '失败';
        }
    }

    public function del_g(){
        $shops = Db::table('yf_shop')->field('id')->select();
        foreach ($shops as $k=>$v){
            $ids = [];
            $sql = '';
            $sql = 'select id from yf_goods where id in (select  id  from  yf_goods  group  by  tb_id,shop_id  having shop_id='.$v['id'].' AND count(id) > 1)';
            $ids = Db::query($sql);
            if (!empty($ids)){
                $arr = [];
                foreach ($ids as $key=>$val){
                    $arr[]=$val['id'];
                }
                Db::table('yf_goods')->where(['id'=>['in',$arr]])->delete();
            }
        }
    }

    public function download(){
        if(strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone')||strpos($_SERVER['HTTP_USER_AGENT'], 'iPad')){
            //重定向到指定的URL地址 并且使用302
            $url= 'https://itunes.apple.com/cn/app/id1360225401?mt=8';
        }else if(strpos($_SERVER['HTTP_USER_AGENT'], 'Android')){
            //重定向到指定的URL地址 并且使用302
            $url= 'https://www.baidu.com';
        }else{
            $url= 'http://www.vipbuy360.com';
        }
        //重定向到指定的URL地址 并且使用302
        $this->redirect($url,302);
    }

    public function ratesurl(){
        $data = \app\api\common\Goods::ratesurl(['itemid'=>'542889436428']);
        halt($data);
    }

    public function get_tkdatas(){
        $url = 'http://pub.alimama.com/items/channel/qqhd.json?channel=qqhd&toPage=1&perPageSize=50&shopTag=&t=1525398101052';
//        $url = 'http://pub.alimama.com/items/search.json?q=%e7%94%b7%e8%a3%85&_t=1525313458290&auctionTag=&perPageSize=50&shopTag=yxjh&t=1525313458292&_tb_token_=e99eb1768875&pvid=10_120.36.212.252_689_1525313353007';
        $url_refer = 'https://item.taobao.com';
        $ch = curl_init();
        //设置选项
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
        curl_setopt($ch, CURLOPT_REFERER, $url_refer);
        $header = array();
        $header[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8';
        $header[] = 'Accept-Language: zh-CN,zh;q=0.8';
        $header[] = 'Cache-Control: max-age=0';
        $header[] = 'Connection: keep-alive';
        $header[] = 'Cookie: uc3=nk2=0M56YNYN%2BA4%3D&id2=W8rr4uUwfV5Z&vt3=F8dAT%2B%2BMdeVt9sjBn%2Bk%3D&lg2=WqG3DMC9VAQiUQ%3D%3D; lgc=%5Cu695A%5Cu5929%5Cu5B9D%5Cu9676; tracknick=%5Cu695A%5Cu5929%5Cu5B9D%5Cu9676; t=45643498fa8ff940a0534abf468c496b; _tb_token_=5touPdVYykOo; cookie2=9cc3ace3ba141f7e0e950da7b4782eae; tt=segmentfault.com; res=scroll%3A1349*6222-client%3A1349*667-offset%3A1349*6222-screen%3A1366*768; pnm_cku822=055UW5TcyMNYQwiAiwQRHhBfEF8QXtHcklnMWc%3D%7CUm5Ockt1T3BEf0N%2BSnJPciQ%3D%7CU2xMHDJ7G2AHYg8hAS8WKQcnCVU0Uj5ZJ11zJXM%3D%7CVGhXd1llXGJYZ1NoVGldZVhlUm9NeEd9SHFFfElyR35Be0N%2FR2k%2F%7CVWldfS0TMwY8ACAcKQkncVU4XSNKGn9AZE8BUDxQCW4PIXch%7CVmhIGCUFOBgkGiMXNwwzDDMTLxEqETELMAUlGSccJwc9AjdhNw%3D%3D%7CV25Tbk5zU2xMcEl1VWtTaUlwJg%3D%3D; cq=ccp%3D1; l=AikpB1ewOIvOADHsO87Aa9qtuduD9B0s; otherx=e%3D1%26p%3D*%26s%3D0%26c%3D0%26f%3D0%26g%3D0%26t%3D0; swfstore=142738; isg=4C03295B995DB1CB7ADB1CC702592A48';
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        //执行并获取HTML文档内容
        $data = curl_exec($ch);
        curl_close($ch);
        $datas = json_decode($data,true);
        halt($datas['data']['pageList']);
    }


    public function searcg_goods(){
        $page = input('page',1);
        if (isset($param['sort']) && $param['sort'] != ''){
            $sort = $param['sort'];
        }else{
            $sort = 0;
        }
        if ($sort == 0){
            $order_condition = 'tk_total_sales_desc';
        }else if ($sort == 1){
            $order_condition = 'price_asc';
        }else if ($sort == 2){
            $order_condition = 'price_desc';
        }else if($sort == 3){
            $order_condition = 'total_sales_desc';
        }else{
            $order_condition = 'start_time desc';
        }
        $c = new \TopClient();
        $c->appkey = '24635648';
        $c->secretKey = 'e3c6f335ca39011870018a730503de72';
        $req = new \TbkScMaterialOptionalRequest();
        $req->setStartDsr("10"); //店铺dsr评分，筛选高于等于当前设置的店铺dsr评分的商品0-50000之间
        $req->setPageSize("20"); //页大小，默认20，1~100
        $req->setPageNo($page); //第几页，默认：１
        $req->setPlatform("1"); //链接形式：1：PC，2：无线，默认：１
        //$req->setEndTkRate("1234"); //淘客佣金比率上限，如：1234表示12.34%
        //$req->setStartTkRate("1234"); //淘客佣金比率下限，如：1234表示12.34%
        //$req->setEndPrice("10"); //折扣价范围上限，单位：元
        //$req->setStartPrice("10"); //折扣价范围下限，单位：元
        $req->setIsOverseas("false"); //是否海外商品，设置为true表示该商品是属于海外商品，设置为false或不设置表示不判断这个属性
        $req->setIsTmall("false"); //是否商城商品，设置为true表示该商品是属于淘宝商城商品，设置为false或不设置表示不判断这个属性
        $req->setSort("tk_rate_des"); //排序_des（降序），排序_asc（升序），销量（total_sales），淘客佣金比率（tk_rate）， 累计推广量（tk_total_sales），总支出佣金（tk_total_commi），价格（price）
        //$req->setItemloc("杭州"); //所在地
        //$req->setCat("16,18"); //后台类目ID，用,分割，最大10个，该ID可以通过taobao.itemcats.get接口获取到
        $req->setQ($param['keyword']); //查询词
        $req->setAdzoneId("125494351"); //	adzone_id
        $req->setAdzoneId("125494351"); //	adzone_id
        $req->setSiteId("35350242"); //site_id 公司
        $req->setSiteId("35350242"); //site_id
        $req->setHasCoupon("false"); //是否有优惠券，设置为true表示该商品有优惠券，设置为false或不设置表示不判断这个属性
        $resp = $c->execute($req, '6202817f9acd8973c21fc4fe0ZZ7e383062fbfcf0135225642623368');  //公司的号
//        $resp = $c->execute($req, '62009276b7ca0e8e9a6a28c9c2c2d7af302ZZdf0ebc42d5810608219'); //自己的号
        $data = object_array($resp);
        $info = [];
        $info['total'] = intval($data['total_results']);
        $info['per_page'] = 20;
        $info['current_page'] = intval(input('page',1));
        $info['last_page'] = intval(ceil($data['total_results']/20));
        if (!empty($data['result_list']['map_data'])){
            foreach ($data['result_list']['map_data'] as $k=>$v){
                if (!empty($v['coupon_info'])){
                    $t1 = mb_strpos($v['coupon_info'],'减');
                    $t2 = mb_strpos($v['coupon_info'],'元');
                    $info['data'][$k]['itemendprice'] = strval($v['zk_final_price'] - mb_substr($v['coupon_info'],$t1+1,$t2-$t1));
                    $info['data'][$k]['couponurl'] = 'https://uland.taobao.com/coupon/edetail?activityId='.$v['coupon_id'].'&itemId='.$v['num_iid'].'&src=cd_cdll';
                }else{
                    $info['data'][$k]['itemendprice'] = $v['zk_final_price'];
                    $info['data'][$k]['couponurl']='';
                }
                $info['data'][$k]['itemid'] = $v['num_iid'];
                $info['data'][$k]['itemtitle'] = $v['title'];
                $info['data'][$k]['itemprice'] = $v['zk_final_price'];
                $info['data'][$k]['itempic'] = $v['pict_url'];
                $info['data'][$k]['shoptype'] = $v['user_type'] == 1 ? 'B':'C';
                $info['data'][$k]['itemsale'] = $v['volume'];
            }
        };
        halt($info);
    }

    public function ter(){
        $sort = input('param.sort',0);
        $keyword = input('param.keyword','');
        $data = \app\api\common\Goods::tbsearch(['keyword'=>$keyword,'sort'=>$sort]);
        return json($data);
    }

    public function re(){
        $data = tbrefresh(['refresh_token'=>'6201020cb18476a4d984d4f5f121ZZf083669ba1536b22f642623368','taobao_user_id'=>'642623368','id'=>'3']);
        halt($data);
    }
    public function pri(){
        $itemid = input('param.id',0);
        $c = new \TopClient();
        $c->appkey = '24635648';
        $c->secretKey = 'e3c6f335ca39011870018a730503de72';
        $req = new \TbkPrivilegeGetRequest();
        $req->setItemId($itemid);
        $req->setAdzoneId("125494351");
        $req->setPlatform("1");
        $req->setSiteId("35350242");
//        $req->setMe("m%3D2%26s%3D94BYV45NHwgcQipKwQzePOeEDrYVVa64LKpWJ%2Bin0XLjf2vlNIV67pL2V8ikcqW7FfrEfJ4hp2q5rze35H1YEElKMSinFVD02hfsaefZn7H4%2Ff3V");
        $resp = $c->execute($req, '62018090a0c0469dace4fe45ce4487eb166e2b9152f9df1642623368');
        $data = object_array($resp);
        halt($data);
    }
    public function category_v2(){
        $data = \app\api\common\Goods::category_v2(['cat_id'=>1]);
        halt($data['data']);
    }

    public function tye(){
        $data = \app\api\common\Index::recommend(['recommend_cate'=>2]);
       return json($data);
    }

    public function good_detail(){
        $data = \app\api\common\Commodity::goods_detail(['itemid'=>564881395857]);
        halt($data);
    }

    public function subject(){
        $data = \app\api\common\Goods::subject_item(['subject_id'=>1]);
        return json($data);
    }

    public function goods_search(){
        $data = \app\api\common\Shop::goods_search(['shop_id'=>23,'keyword'=>'女装']);
        halt($data['data']);
    }

    public function good_index(){
        $data = \app\api\common\Shop::index(['shop_id'=>80]);
        halt($data['data']);
    }

    public function get_detail(){
        $shoptype = input('param.shoptype','C');
        $itemid = input('param.itemid',0);
        if ($shoptype == 'B'){
            $goods_url = 'https://detail.tmall.com/item.htm?id='.$itemid;
        }else{
            $goods_url = 'https://item.taobao.com/item.htm?id='.$itemid;
        }
        $url = 'http://pub.alimama.com/items/search.json?q='.urlencode($goods_url);
        $data = file_get_contents($url);
        $arr = json_decode($data,true);

        $info['itemid'] = $arr['data']['pageList'][0]['auctionId'];
        $info['itemtitle'] = $arr['data']['pageList'][0]['title'];
        $info['itemdesc'] = '';
        $info['itemprice'] = $arr['data']['pageList'][0]['zkPrice'];
        $info['itemsale'] = $arr['data']['pageList'][0]['biz30day'];
        $info['itempic'] = 'http:'.$arr['data']['pageList'][0]['pictUrl'];
        if ($arr['data']['pageList'][0]['couponInfo'] == '无'){
            $info['itemendprice'] = $arr['data']['pageList'][0]['zkPrice'];
            $info['couponstarttime'] = '';
            $info['couponendtime'] = '';
            $info['couponmoney'] = 0;
        }else{
            $info['itemendprice'] = $arr['data']['pageList'][0]['zkPrice'] - $info['itemendprice'] = $arr['data']['pageList'][0]['couponAmount'];
            $info['couponstarttime'] = $arr['data']['pageList'][0]['couponEffectiveStartTime'];
            $info['couponendtime'] = $arr['data']['pageList'][0]['couponEffectiveEndTime'];
            $info['couponmoney'] = $arr['data']['pageList'][0]['couponAmount'];
        }
        $info['shoptype'] = $shoptype;
        halt($info);
    }



}
